
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export const store = new Vuex.Store({
  state: {
    activeIndex: localStorage.getItem('activeIndex') || '',
    options: JSON.parse(localStorage.getItem('tabs')) || [],
    btnData: []
  },
  getters: {
    get_active_index (state) {
      return state.activeIndex
    }
  },
  mutations: {
    set_active_index (state, value) {
      state.activeIndex = value
      localStorage.setItem('activeIndex', value)
    },
    add_tabs (state, data) {
      if (state.options.length === 0) {
        state.options.push(data)
      } else {
        let tabs = state.options
        for (let i = 0; i < tabs.length; i++) {
          let tab = tabs[i]
          if (data.route === tab.route) {
            return
          }
        }
        state.options.push(data)
      }
      localStorage.setItem('tabs', JSON.stringify(state.options))
    },
    clear_tabs (state) {
      state.options = []
      localStorage.setItem('tabs', JSON.stringify(state.options))
    },
    delete_tabs (state, route) {
      let index = 0
      for (let option of state.options) {
        if (option.route === route) {
          break
        }
        index++
      }
      state.options.splice(index, 1)
      localStorage.setItem('tabs', JSON.stringify(state.options))
    },
    getBtndata (state, data) {
      state.btnData = data
    }
  },
  actions: {
    setAction (context, value) {
      context.commit('set_active_index', value)
    },
    addAction (context, data) {
      context.commit('add_tabs', data)
    },
    cleartAction (context) {
      context.commit('clear_tabs')
    },
    deleteAction (context, route) {
      context.commit('delete_tabs', route)
    }
  }
})
